'use strict';
var mysql = require('mysql');
var mysqlConfig = {
	host: '192.168.0.156',
    user: 'root',
    password: 'trueway',
    database:'truechart',
    port:3306
}


var oracleDb = require('./class_oracledb').createTester();

//表名
var _prev = 'tc_';
var tableNames = {
	modelList:_prev+'modellist',
	tableList:_prev+'tablelist',
	fieldList:_prev+'fieldlist',
	viewList:_prev+'viewlist',
	valueList:_prev+'valuelist'
}
var Sqls = {
	viewlist:"select t.VIEW_NAME,c.COMMENTS from user_views t join user_tab_comments c on c.table_name = t.VIEW_NAME where t.VIEW_NAME like 'SHOW%'"
	,fieldlist:"select c.COLUMN_NAME,m.COMMENTS from user_tab_columns c left join user_col_comments m on  c.TABLE_NAME = m.TABLE_NAME and c.COLUMN_NAME = m.COLUMN_NAME where  c.TABLE_NAME ='{$viewName}'"
	,getresult:"select {$fieldName} from {$viewName}"
}

exports.mainInit = function() {
	return new Main();
};

function Main() {
	
}

var fs = require('fs');
function readFile(file){
	var data = fs.readFileSync(file,"utf-8");
	//console.log(data);
	return data;
}
function writeFile(file,data,callback){
	fs.writeFile(file, data, {encoding:'utf-8'}, callback);
}
function generateMixed(n) {
	var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
	var res = "";
	for(var i = 0; i < n ; i ++) {
		var id = Math.ceil(Math.random()*35);
	 	res += chars[id];
	}
	return res;
}

var template_file = __dirname+'/public/chart-before.html';
var template_file2 = __dirname+'/public/chart-after.html';
var chart_html = __dirname+'/public/chart_html';
var return_html = '/chart_html';

Main.prototype = {
	// 初始化
	init:function(app){
		console.log('ch-main-init-------------->>>>>>>>>>>>>>>');
		this.app = app;
		//链接数据库
		//this.connection = mysql.createConnection(mysqlConfig);
		this.mysqlpool = mysql.createPool(mysqlConfig);
		this.apiList();
	},
	conn:function(){
		//通过取到的配置去链接对应的库
		oracleDb.setting({
			user: 'workflow_tzwspj',
			password: 'trueway2016',
			connectString: 'ORCL_192.168.0.137'
		});
	},
	//http接口列表
	apiList:function(){
		var that = this;
		
		//获取视图
		this.app.get('/getViewList', function(req, res) {
			that.conn();
			if(req.query.modelId){
				var modelId = req.query.modelId;
				oracleDb.query(Sqls.viewlist, [], function(rows, msg){
					var returnobj = {
						"error":null,
						"success":true,
						"data":[]
					};
					if(msg!==null){
						returnobj.error = msg;
						returnobj.success = false;
					}
					var arr=[];
					if(rows){
						for(var i=0,l=rows.length;i<l;i++){
							arr.push({
								"modelId":modelId,
								"viewName":rows[i][0],
								"viewNameCN":rows[i][1]
							});
						}
					}
					returnobj.data = arr;
					res.send(returnobj);
				});
			}else{
				res.send({
					"error":"参数异常",
					"success":false,
					"data":[]
				});
			}
		});
		
		//获取字段
		this.app.get('/getFieldList', function(req, res) {
			that.conn();
			if(req.query.viewName){
				var modelId = req.query.modelId;
				var viewName = req.query.viewName;
				oracleDb.query(Sqls.fieldlist.replace("{$viewName}",viewName), [], function(rows, msg){
					var returnobj = {
						"error":null,
						"success":true,
						"data":[]
					};
					if(msg!==null){
						returnobj.error = msg;
						returnobj.success = false;
					}
					var arr=[];
					if(rows){
						for(var i=0,l=rows.length;i<l;i++){
							arr.push({
								"modelId":modelId,
								"viewName":viewName,
								"fieldName":rows[i][0],
								"fieldNameCn":rows[i][1]
							});
						}
					}
					returnobj.data = arr;
					res.send(returnobj);
				});
			}else{
				res.send({
					"error":"参数异常",
					"success":false,
					"data":[]
				});
			}
		});
		
		//取值
		this.app.get('/getResult', function(req, res) {
			that.conn();
			if(req.query.fieldName){
				var modelId = req.query.modelId;
				var viewName = req.query.viewName;
				var fieldName = req.query.fieldName;
				var fieldNameCn = req.query.fieldNameCn;
				var sql = Sqls.getresult.replace("{$viewName}",viewName);
				sql = sql.replace("{$fieldName}",fieldName);
				if(req.query.vd){
					var vd = req.query.vd;
					vd = JSON.parse(vd);
					var orderName = vd[0];
					sql = sql +" order by "+orderName+" asc";
				}
				oracleDb.query(sql, [], function(rows, msg){
					var returnobj = {
						"error":null,
						"success":true,
						"data":[]
					};
					if(msg!==null){
						returnobj.error = msg;
						returnobj.success = false;
					}
					var arr=[];
					if(rows){
						for(var i=0,l=rows.length;i<l;i++){
							arr.push({
								"modelId":modelId,
								"viewName":viewName,
								"fieldName":fieldName,
								"fieldNameCn":fieldNameCn,
								"fieldType":"number",
								"value":rows[i][0]
							});
						}
					}
					returnobj.data = arr;
					res.send(returnobj);
				});
			}else{
				res.send({
					"error":"参数异常",
					"success":false,
					"data":[]
				});
			}
		});
		
		//发布
		this.app.post('/fabuHtml', function(req, res) {
			that.conn();
			if(req.body.option){
				var option = req.body.option;
				var chart_x = req.body.chart_x;
				var chart_y = req.body.chart_y;
				var chart_type = req.body.chart_type;
				var modelId = req.body.modelId;
				//存储mysql
				//生成html
				//1.读取模板
				var temp_file_data = readFile(template_file);
				var temp_file_data2 = readFile(template_file2);
				//2.替换变量
				if(temp_file_data){
					var new_html_data = temp_file_data.toString() + "'" + option + "';var chart_x="+chart_x+";var chart_y="+chart_y+";var chart_type='"+chart_type+"';var modelId="+modelId + temp_file_data2.toString();
					var temp = generateMixed(8)+'.html';
					var day = (new Date()).pattern("yyyy-MM-dd");
					var file_name = chart_html+'/'+day+'-'+temp;
					var return_name = return_html+'/'+day+'-'+temp;
					//3.写入html文件
					writeFile(file_name,new_html_data,function(r){
						if(r==null){
							//返回地址
							res.send({
								"error":null,
								"success":true,
								"data":[return_name]
							});
						}else{
							res.send({
								"error":r,
								"success":false,
								"data":[]
							});
						}
					});
				}else{
					res.send({
						"error":"模板读取异常",
						"success":false,
						"data":[]
					});
				}
			}else{
				res.send({
					"error":"请求非法",
					"success":false,
					"data":[]
				});
			}
		});
		
		//预览
		this.app.post('/preViewHtml', function(req, res) {
			that.conn();
			if(req.body.option){
				var option = req.body.option;
				var chart_x = req.body.chart_x;
				var chart_y = req.body.chart_y;
				var chart_type = req.body.chart_type;
				var modelId = req.body.modelId;
				//存储mysql
				//生成html
				//1.读取模板
				var temp_file_data = readFile(template_file);
				var temp_file_data2 = readFile(template_file2);
				//2.替换变量
				if(temp_file_data){
					var new_html_data = temp_file_data.toString() + "'" + option + "';var chart_x="+chart_x+";var chart_y="+chart_y+";var chart_type='"+chart_type+"';var modelId="+modelId + temp_file_data2.toString();
					var temp = 'preView.html';
					var day = '';
					var file_name = chart_html+'/'+temp;
					var return_name = return_html+'/'+temp;
					//3.写入html文件
					writeFile(file_name,new_html_data,function(r){
						if(r==null){
							//返回地址
							res.send({
								"error":null,
								"success":true,
								"data":[return_name]
							});
						}else{
							res.send({
								"error":r,
								"success":false,
								"data":[]
							});
						}
					});
				}else{
					res.send({
						"error":"模板读取异常",
						"success":false,
						"data":[]
					});
				}
			}else{
				res.send({
					"error":"请求非法",
					"success":false,
					"data":[]
				});
			}
		});
		
	},
	//查询接口
	mysqlQuery:function(sql,callback){
		var that = this;
		//this.connection.connect();
		this.mysqlpool.getConnection(function(err,conn){
	        if(err){
	            callback(err,null,null);
	        }else{
	            conn.query(sql,function(qerr,vals,fields){
	                //释放连接
	                conn.release();
	                //事件驱动回调
	                callback(qerr,vals,fields);
	            });
	        }
	    });
	}
};

/**
 * 对Date的扩展，将 Date 转化为指定格式的String 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
 * 可以用 1-2 个占位符 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) eg: (new
 * Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 (new
 * Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04 (new
 * Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04 (new
 * Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04 (new
 * Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
Date.prototype.pattern = function(fmt) {
	var o = {
		"M+" : this.getMonth() + 1, // 月份
		"d+" : this.getDate(), // 日
		"h+" : this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, // 小时
		"H+" : this.getHours(), // 小时
		"m+" : this.getMinutes(), // 分
		"s+" : this.getSeconds(), // 秒
		"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
		"S" : this.getMilliseconds()
	// 毫秒
	};
	var week = {
		"0" : "\u65e5",
		"1" : "\u4e00",
		"2" : "\u4e8c",
		"3" : "\u4e09",
		"4" : "\u56db",
		"5" : "\u4e94",
		"6" : "\u516d"
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	}
	if (/(E+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1,
				((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "")
						: "")
						+ week[this.getDay() + ""]);
	}
	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
					: (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
};